float2 halfPixel;
float4x4 InverseProjection;

texture depthMap; 

sampler depthSampler = sampler_state
{
    Texture = (depthMap);
    AddressU = CLAMP;
    AddressV = CLAMP;
    MagFilter = POINT;
    MinFilter = POINT;
    Mipfilter = POINT;
};

struct VertexShaderInput
{
    float3 Position : POSITION0;
    float2 TexCoord : TEXCOORD0;
};

struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 TexCoord : TEXCOORD0;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;

    output.Position = float4(input.Position, 1);
    output.TexCoord = input.TexCoord - halfPixel;

    return output;
}

float FogStart;
float FogEnd;
float3 FogColor;

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    float z = tex2D(depthSampler, input.TexCoord);
	float x = input.TexCoord.x * 2.0 - 1.0;
	float y = (1 - input.TexCoord.y) * 2.0 - 1.0;

	float4 vpos = float4(x, y, z, 1.0f);
	vpos = mul(vpos, InverseProjection);
	vpos /= vpos.w;

    float distance = length(vpos.xyz);

    float lerp = saturate((distance - FogStart)/(FogEnd - FogStart));

    return float4(FogColor, lerp);
}

technique Fog
{
    pass Pass1
    {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}
